<?php
namespace addon\kindeditor\logic;
use think\Request;
use tpfcore\storage\AliyunOss;
use tpfcore\Core;
/**
 * 编辑器逻辑
 */
class Editor
{
    /**
     * 图片上传
     */
    public function pictureUpload()
    {

        $upload_position = empty(config("config.upload_pic_position"))?"local":config("config.upload_pic_position");

        // 上传到本地
        if($upload_position=="local"){

            $size=empty(config("config.allow_upload_pic_size"))?2*1024*1024:config("config.allow_upload_pic_size")*1024;

            $ext=empty(config("config.allow_upload_pic_type"))?'jpg,png,gif':config("config.allow_upload_pic_type");

            $object = request()->file('imgFile');

            $info = $object->validate(['size'=>$size,'ext'=>$ext])->move(UPLOAD_PATH . 'editor');

            $result  = ['error' => DATA_DISABLE, 'url' => '']; 
            
            if ($info) {

                $save_name = $info->getSaveName();
                
                $picture_dir_name = substr($save_name, 0, strrpos($save_name, DS));
                
                $filename = $info->getFilename();
                
                $result['url'] = UPLOAD_PATH_RELATIVE . "editor/".$picture_dir_name."/".$filename;

                $result['img_url'] = "/data/uploads/"."editor/".$picture_dir_name."/".$filename;

            } else {
                
                $result['error'] = DATA_NORMAL;

                $result['message'] = $object->getError();
            }
            return $result;

        }
        //上传到阿里云
        elseif ($upload_position=="aliyun_oss") {

            $listConfig = Core::loadAddonModel("AliyunOss","aliyun_oss","controller")->getConfig("aliyun_oss");

            if(empty($listConfig) || $listConfig['status']==0){
                return ["error"=>DATA_NORMAL,"message"=>"请先安装或配置好OSS"];
            }

            $config = json_decode($listConfig['config'],true);

            $list = Core::loadAddonModel("OssBucket","aliyun_oss","controller")->getOssBucket(["order"=>"is_default desc","limit"=>1]);

            if(empty($list)){

                return ["error"=>DATA_NORMAL,"message"=>"请配置好你的bucket"];
            }

            $config["config"]['endpoint']=$list[0]['endpoint'];

            try {

                $aliyun_oss = new AliyunOss($config['config']);

                if(!$aliyun_oss->upload()){

                    return ["error"=>DATA_NORMAL,"message"=>$aliyun_oss->getErrorMsg()];

                }

                print_r($aliyun_oss->getUploadFileInfo());

            } catch (\Exception $e) {

                return ["error"=>DATA_NORMAL,"message"=>$e->getMessage()];

            }
        }
        else{
            $result['error'] = DATA_NORMAL;

            $result['message'] = "请先设置好图片保存位置";

            return $result;
        }


    }
}
